from sqlalchemy import Column, Integer, String, DateTime
from sqlalchemy.orm.session import Session

from airflow.models.base import Base
from airflow.models.idata_project_datasource import ProjectDatasource
from airflow.models.idata_project_user import ProjectUser
from airflow.utils.session import provide_session


class Datasource(Base):
    """the class to get user info."""

    __tablename__ = "idata_datasource"
    __table_args__ = {"useexisting": True}

    id = Column(Integer, primary_key=True, autoincrement=True)
    name = Column(String(255))
    ip = Column(String(255))
    port = Column(Integer)
    user_name = Column(String(255))
    password = Column(String(255))
    type = Column(Integer)
    create_time = Column(DateTime)
    oa_user_name = Column(String(64))

    @staticmethod  # 静态方法
    @provide_session
    def get_datasource(datasource_id, session: Session = None):
        return session.query(Datasource).filter(Datasource.id == datasource_id).first()

    @staticmethod
    @provide_session
    def get_datasources(project_id, datasource_type, session: Session = None):
        q = session.query(Datasource).outerjoin(ProjectDatasource, Datasource.id == ProjectDatasource.datasource_id)
        if project_id:
            q = q.filter(ProjectDatasource.project_id == project_id)
        if datasource_type:
            q = q.filter(Datasource.type == datasource_type)
        return q.all()

    @staticmethod
    @provide_session
    def get_datasources_page(page, project_id, datasource_type, session: Session = None):
        q = session.query(Datasource).outerjoin(ProjectDatasource, Datasource.id == ProjectDatasource.datasource_id)
        if project_id:
            q = q.filter(ProjectDatasource.project_id == project_id)
        if datasource_type:
            q = q.filter(Datasource.type == datasource_type)
        return q.paginate(page, 10, error_out=False)

    @staticmethod
    @provide_session
    def add_datasource(datasource, session: Session = None):
        return session.add(datasource)

    @staticmethod
    @provide_session
    def delete_datasource(datasource_id, session: Session = None):
        session.query(Datasource).filter(Datasource.id == datasource_id).delete()

    @staticmethod
    @provide_session
    def update_datasource(datasource, session: Session = None):
        result = session.query(Datasource).filter(Datasource.id == datasource.id).first()
        if result is None:
            return
        else:
            return session.merge(datasource)

    def to_json(self):
        if self is None:
            return None
        data = {
            'id': self.id,
            'name': self.name,
            'ip': self.ip,
            'port': self.port,
            'user_name': self.user_name,
            'password': self.password,
            'type': self.type,
            'create_time': self.create_time,
            'oa_user_name': self.oa_user_name
        }
        return data
